const app = getApp()
const { get, post } = require('../../utils/request')
const Toast = require('tdesign-miniprogram/toast/index');

Page({
  data: {
    addressList: [],
    loading: false,
    current: 1,
    pageSize: 20,
    total: 0,
    hasMore: true,
    refreshing: false,
    loadingProps: {
      size: '50rpx',
    },
    right: [
      {
        text: '编辑',
        className: 'edit',
      },
      {
        text: '删除',
        className: 'delete',
      },
    ],
    isSelectMode: false,
  },

  onLoad(options) {
    this.getAddressList()
    // 检查是否为选择模式
    if (options && options.select) {
      this.setData({
        isSelectMode: true
      })
    }
  },

  onShow() {
    this.getAddressList()
  },

  onPullDownRefresh() {
    this.setData({
      refreshing: true,
      current: 1,
      addressList: []
    }, () => {
      this.getAddressList().then(() => {
        this.setData({ refreshing: false });
      });
    });
  },

  onReachBottom() {
    this.loadMore();
  },

  onScroll(e) {
    // 可以在这里处理滚动事件
  },

  onActionClick(e) {
    const { index } = e.detail;
    const id = e.currentTarget.dataset.id;

    if (index === 0) {
      // 编辑操作
      this.editAddress({ currentTarget: { dataset: { id } } });
    } else if (index === 1) {
      // 删除操作
      this.deleteAddress({ currentTarget: { dataset: { id } } });
    }
  },

  // 获取地址列表
  async getAddressList() {
    this.setData({ loading: true })
    try {
      const params = {
        current: this.data.current,
        pageSize: this.data.pageSize
      }
      const res = await post('/api/address/my/list/page/vo', params)
      if (res.code === 0 && res.data) {
        let newList = [];
        if (this.data.current === 1) {
          newList = res.data.records || [];
        } else {
          newList = [...this.data.addressList, ...(res.data.records || [])];
        }

        this.setData({
          addressList: newList,
          total: res.data.total || 0,
          hasMore: res.data.current * res.data.size < res.data.total
        })
      }
    } catch (error) {
      console.error('获取地址列表失败', error)
      Toast({
        context: this,
        selector: '#t-toast',
        message: '获取地址列表失败',
        theme: 'error',
      });
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载更多
  loadMore() {
    if (!this.data.hasMore || this.data.loading) return;

    this.setData({
      current: this.data.current + 1
    }, () => {
      this.getAddressList();
    });
  },

  // 新增地址
  addAddress() {
    wx.navigateTo({
      url: '/pages/address/edit/edit'
    })
  },

  // 编辑地址
  editAddress(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/address/edit/edit?id=${id}`
    })
  },

  // 删除地址
  async deleteAddress(e) {
    const id = e.currentTarget.dataset.id

    wx.showModal({
      title: '提示',
      content: '确定要删除该地址吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const result = await post('/api/address/delete', { id })
            if (result.code === 0 && result.data) {
              Toast({
                context: this,
                selector: '#t-toast',
                message: '删除成功',
                theme: 'success',
              });
              this.setData({
                current: 1,
                addressList: []
              }, () => {
                this.getAddressList();
              });
            } else {
              Toast({
                context: this,
                selector: '#t-toast',
                message: result.message || '删除失败',
                theme: 'error',
              });
            }
          } catch (error) {
            console.error('删除地址失败', error)
            Toast({
              context: this,
              selector: '#t-toast',
              message: '删除地址失败',
              theme: 'error',
            });
          }
        }
      }
    })
  },

  // 设为默认地址
  async setDefaultAddress(e) {
    const id = e.currentTarget.dataset.id
    try {
      const result = await post(`/api/address/set/default/${id}`)
      if (result.code === 0 && result.data) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '设置成功',
          theme: 'success',
        });
        this.setData({
          current: 1,
          addressList: []
        }, () => {
          this.getAddressList();
        });
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: result.message || '设置失败',
          theme: 'error',
        });
      }
    } catch (error) {
      console.error('设置默认地址失败', error)
      Toast({
        context: this,
        selector: '#t-toast',
        message: '设置默认地址失败',
        theme: 'error',
      });
    }
  },

  // 选择地址
  selectAddress(e) {
    // 如果不是选择模式，则不处理
    if (!this.data.isSelectMode) return;

    const id = e.currentTarget.dataset.id;
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2]; // 上一个页面

    if (prevPage && prevPage.setSelectedAddress) {
      // 获取选中的地址详情
      const selectedAddress = this.data.addressList.find(item => item.id === id);

      // 调用上一个页面的方法，传递选中的地址
      prevPage.setSelectedAddress(selectedAddress);

      // 返回上一页
      wx.navigateBack();
    }
  }
}) 